//
//  MBDTextEditCell.swift
//  MasterBoy
//
//  Created by kyson on 2023/10/25.
//

import Foundation
import UIKit
import YYText


class MBDTextEditCell: MBDCommonCell,UITextFieldDelegate {
    var infoEditTextField : UITextField!
    var tipsLabel : YYLabel!
    private var isLocationToEnd: Bool = false

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.initialize()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        
        self.initialize()
    }
    
    override var cellModel: Any! {
        didSet {
            let realCellModel = self.cellModel as! MBDModifyInfoTextFieldEditCellModel
            realCellModel.cellWillDisplayBlock =  { ()->Void in
                self.infoEditTextField.becomeFirstResponder()
            }
            self.infoEditTextField.text = realCellModel.text
            self.tipsLabel.text = String(format: "%d",realCellModel.textLimit ?? 0)
            self.updateTips()
        }
    }
    
    func initialize() {
        self.commonBackgroundView.setDynamicForgroundColor()
        self.contentView.setDynamicForgroundColor()
        self.separateLine.isHidden = true
        
        infoEditTextField = UITextField()
        infoEditTextField.setDynamicForgroundColor()
        infoEditTextField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)

        infoEditTextField.delegate = self
        
        let button = UIButton(frame: CGRectMake(0, 0, 44, 44))
        button.setImage(UIImage(named: "delete"), for: .normal)
        infoEditTextField.rightView = button
        self.commonBackgroundView.addSubview(infoEditTextField)
        
        let tipsBackgroundView = UIView()
        tipsBackgroundView.setDynamicForgroundColor()
        self.commonBackgroundView.addSubview(tipsBackgroundView)
        
        tipsLabel = YYLabel()
        tipsLabel.textColor = UIColor.gray
        tipsLabel.font = UIFont.systemFont(ofSize: 12)
        tipsLabel.textAlignment = .right
        self.commonBackgroundView.addSubview(tipsLabel)
        tipsBackgroundView.snp.makeConstraints { make in
            make.top.equalTo(infoEditTextField.snp.bottom)
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.bottom.equalToSuperview()
        }
        
        tipsLabel.snp.makeConstraints { make in
            make.edges.equalTo(tipsBackgroundView)
        }
        
        infoEditTextField.snp.makeConstraints { make in
            make.left.equalTo(self.commonBackgroundView)
            make.top.equalTo(self.commonBackgroundView)
            make.bottom.equalTo(self.commonBackgroundView).offset(-36)
            make.right.equalTo(self.commonBackgroundView)
        }
    }
    
    private func updateTips(){
        let realCellModel = self.cellModel as! MBDModifyInfoTextFieldEditCellModel

        if let realText = realCellModel.text {
            tipsLabel.text = String(realCellModel.textLimit! - realText.count)
        }
        if Int(tipsLabel.text!) ?? 0 > 0 {
            tipsLabel.textColor = UIColor.gray
        } else {
            tipsLabel.textColor = UIColor.red
        }
    }
    
    @objc func textFieldDidChange(_ textField: UITextField) {
        let realCellModel = self.cellModel as! MBDModifyInfoTextFieldEditCellModel
        realCellModel.text = textField.text
        self.updateTips()
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString text: String) -> Bool {
        if text == "" { // 删除字数
            return true
        }
        let realCellModel = self.cellModel as! MBDModifyInfoTextFieldEditCellModel
        let maxWordsCount = realCellModel.textLimit!
            
        let inputMode = UITextInputMode.activeInputModes.first?.primaryLanguage
        if inputMode == "zh-Hans" || inputMode == "zh-Hant" { // 简体/繁体中文输入法(拼音、手写输入等)
            if let selectedRange = textField.markedTextRange,
                let _ = textField.position(from: selectedRange.start, offset: 0) { // 如果有高亮的文本，如拼音、手写
                // 拼音输入：联想的过程中，location时刻变化(高亮文本的尾部位置)，length始终为0
                // 手写输入：联想的过程中不会回调该代理方法，确认联想词后才会进入该代理方法
                if range.length > 0 { // 选中联想词后，location变回高亮文本的起始位置，length为高亮文本的长度，需要对字数限制字数
                    return !limitMaxWordsCount(textField, replacementText: text, isLocationToEnd: false)
                }
            } else { // 没有高亮选择的字，对已输入的文字进行字数限制
                if range.location >= maxWordsCount {
                    self.tipsLabel.textColor = UIColor.red
                    self.tipsLabel.text = "0"
                    return false
                } else { // 处理粘贴引起的字数超限, 截取文本后需要自己去移动光标到尾部
                    return !limitMaxWordsCount(textField, replacementText: text, isLocationToEnd: true)
                }
            }
        } else { // 中文输入法以外的输入法直接进行字数限制
            if range.location >= maxWordsCount {
                self.tipsLabel.textColor = UIColor.red
                self.tipsLabel.text = "0"
                return false
            } else { // 处理粘贴引起的字数超限, 截取文本后需要自己去移动光标到尾部
                return !limitMaxWordsCount(textField, replacementText: text, isLocationToEnd: true)
            }
        }
            
        return true
    }
    

    func textFieldDidChangeSelection(_ textField: UITextField) {
        let realCellModel = self.cellModel as! MBDModifyInfoTextFieldEditCellModel
        let maxWordsCount = realCellModel.textLimit!

        if let text = textField.text, isLocationToEnd, text.utf16.count >= maxWordsCount {
            
            let arbitraryValue: Int = realCellModel.textLimit ?? 0

            if let newPosition = textField.position(from: textField.beginningOfDocument, offset: arbitraryValue) {
                
                textField.selectedTextRange = textField.textRange(from: newPosition, to: newPosition)
                isLocationToEnd = false
            }
        }
    }
    
    func limitMaxWordsCount(_ textField: UITextField, replacementText text: String, isLocationToEnd: Bool) -> Bool {
        let realCellModel = self.cellModel as! MBDModifyInfoTextFieldEditCellModel
        let maxWordsCount = realCellModel.textLimit!
        
        let string = textField.text! + text
        if string.utf16.count > maxWordsCount {
            textField.text = String(string.prefix(maxWordsCount))
            self.isLocationToEnd = isLocationToEnd
            return true
        }
        return false
    }
    
}
